<?php
/**
 * Created by b17
 * 2/29/12 8:21 PM
 */

class SubscribeController extends G4T_Controller
{
    /**
     * @var \Managers\Subscribers
     */
    private $_manager;

    public function init()
    {
        parent::init();
        $this->_manager = new \Managers\Subscribers();
    }

    public function indexAction()
    {
        $form = $this->_getForm();
        $this->view->form = $form;

        if ($this->_request->isPost()) {

            if ($form->isValid($this->_getAllParams())) {
                $values = $form->getValues();
                try {
                    $entity = $this->_manager->create($values);
                    $mail = new \Managers\Mailer\Subscribe($entity);
                    $mail->send();
                    $this->_saveCookie();
                    $this->view->message = "Спасибо за подписку.";
                    $this->view->success = true;
                } catch (LogicException $e) {
                    $this->view->message = $e->getMessage();
                } catch (Exception $e) {
                    $this->view->message = 'Что-то пошло не так.';
                    $this->handleException($e);
                }
            }
        }
    }

    private function _saveCookie()
    {
        setcookie('subscribe', sha1(mt_rand()), time() + 365 * 24 * 3600, '/');
    }

    private function _removeCookie()
    {
        setcookie('subscribe', '', time());
    }

    public function removeAction()
    {
        $result = $this->_manager->unSubscribe($this->_getParam('token'));
        $this->_removeCookie();
        if ($result) {
            $this->_flashMessenger->addMessage('Вы успешно отписались от рассылки.', Lib_Flash::NOTICE, Lib_Flash::LATER);
        } else {
            $this->_flashMessenger->addMessage('Неправильные параметры.');
        }
        $this->_redirect('/');
    }

    private function _getForm()
    {
        $formBuilder = \G4T\Form\FormBuilder::createFormBuilder(\Managers\Subscribers::TABLE, array('id' => 'subscribe-form'))
            ->addField('email', 'email', array('label' => 'Email','style'=> 'width:170px'))
            ->addField('submit', 'submit', array('label' => 'Подписаться','class'=>'btn'));
        return $formBuilder->getForm();
    }
}
